<template>
  <div
      v-if="isVisible"
      ref="overlayRef"
      class="drag-overlay"
      @contextmenu.prevent <!-- Prevent context menu on the overlay -->
  >
  <!-- Overlay is visually transparent but captures mouse events -->
  </div>
</template>

<script setup lang="ts">
import { ref, watch, type Ref } from 'vue';
import { useEventListener, useThrottleFn } from '@vueuse/core';

// --- Props ---
const props = defineProps<{
  isVisible: boolean;
}>();

// --- Emits ---
const emit = defineEmits<{
  (e: 'hover-target-changed', payload: { type: 'breadcrumb' | 'folder' | null; uuid: string | null }): void;
}>();

// --- Refs ---
const overlayRef: Ref<HTMLDivElement | null> = ref(null);
const lastHoveredTarget = ref<{ type: 'breadcrumb' | 'folder' | null; uuid: string | null }>({ type: null, uuid: null });

// --- Mouse Move Handler (Throttled) ---
const handleMouseMove = useThrottleFn((event: MouseEvent) => {
  if (!overlayRef.value || !props.isVisible) return;

  const { clientX, clientY } = event;
  let currentTarget: { type: 'breadcrumb' | 'folder' | null; uuid: string | null } = { type: null, uuid: null };

  // Temporarily hide overlay to peek underneath
  overlayRef.value.style.pointerEvents = 'none';
  const elementsUnderCursor = document.elementsFromPoint(clientX, clientY);
  overlayRef.value.style.pointerEvents = 'auto'; // Restore immediately

  // Find the topmost relevant target
  for (const element of elementsUnderCursor) {
    // Check for Breadcrumb Target
    if (element.classList.contains('breadcrumb-hover-target')) {
      const uuid = (element as HTMLElement).dataset.crumbUuid;
      if (uuid !== undefined) { // Ensure uuid exists
        currentTarget = { type: 'breadcrumb', uuid: uuid === 'root' ? null : uuid };
        // console.log('[DragOverlay] Found breadcrumb target:', currentTarget.uuid);
        break; // Found the topmost relevant target
      }
    }

    // Check for Folder Item Target (using the li element now)
    // We assume DropTargetFolder is inside a li with class 'filesystem-item-li' and data-item-uuid
    if (element.classList.contains('filesystem-item-li')) {
      const liElement = element as HTMLLIElement;
      // Check if it *contains* a folder drop target indicator (or simply check its data type if available)
      // A more robust check might involve looking at the underlying data item type if possible,
      // but for now, we check if it's marked as a folder target via a class or structure.
      // Let's assume the parent `FileManagerView` will add a `data-item-type="folder"` to the li.
      if (liElement.dataset.itemType === 'folder') {
        const uuid = liElement.dataset.itemUuid;
        if (uuid) {
          currentTarget = { type: 'folder', uuid: uuid };
          // console.log('[DragOverlay] Found folder target:', currentTarget.uuid);
          break; // Found the topmost relevant target
        }
      }
    }
  }

  // Emit event only if the target has actually changed
  if (currentTarget.type !== lastHoveredTarget.value.type || currentTarget.uuid !== lastHoveredTarget.value.uuid) {
    // console.log('[DragOverlay] Hover target changed:', currentTarget);
    lastHoveredTarget.value = { ...currentTarget };
    emit('hover-target-changed', currentTarget);
  }
}, 100); // Throttle to 100ms (adjust as needed)

// --- Event Listener ---
// Listen on the overlay itself
useEventListener(overlayRef, 'mousemove', handleMouseMove);
// Also listen for mouse leaving the window entirely
useEventListener(document, 'mouseleave', () => {
  if (props.isVisible) {
    console.log('[DragOverlay] Mouse left window during drag.');
    if (lastHoveredTarget.value.type !== null) {
      lastHoveredTarget.value = { type: null, uuid: null };
      emit('hover-target-changed', { type: null, uuid: null });
    }
  }
});


// --- Watcher ---
watch(() => props.isVisible, (newValue) => {
  if (!newValue) {
    // When overlay becomes hidden, reset the target state
    // console.log('[DragOverlay] Overlay hidden. Resetting target state.');
    if (lastHoveredTarget.value.type !== null) {
      lastHoveredTarget.value = { type: null, uuid: null };
      emit('hover-target-changed', { type: null, uuid: null });
    }
  } else {
    // When overlay becomes visible, ensure initial state is null
    lastHoveredTarget.value = { type: null, uuid: null };
    // Optionally emit null initially? Depends on parent logic.
    // emit('hover-target-changed', { type: null, uuid: null });
  }
});

</script>

<style scoped>
.drag-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  /* High z-index, but potentially below custom drag layers if any */
  z-index: 5000;
  /* Transparent background, but captures events */
  background-color: rgba(0, 0, 0, 0.0); /* Visually transparent */
  /* Ensure it captures mouse events initially */
  pointer-events: auto;
  /* Optional: Add a very subtle visual indicator during debugging */
  /* border: 1px dashed red; */
  /* cursor: grabbing; */ /* Indicate dragging */
}
</style>